<?php
$db = new Database;
$auth = Auth::getAuth('current_user');
$user_id = $auth['id'];
$company_id = $auth['company_id'];
if(isset($_POST['action'])){
    if($_POST['action']=="viewDiagram"){
        $diagram_id = $_POST['diagram_id'];
        $selectObjects = $db->query("SELECT * from tborgchartobjects where orgChart_id = '$diagram_id'","array");
        foreach($selectObjects as $getObjects){
            $object_id = explode("_",$getObjects['object_id']);
            ?>
            <span class="appendShapes flowChartObject appendObjects flowchartToolTip" style="left:<?php echo $getObjects['lefts']; ?>;top:<?php echo $getObjects['tops']; ?>;" id="<?php echo $getObjects['object_id']; ?>" title="<?php echo $getObjects['role']; ?>">
            <textarea class="textInsert" id="text_<?php echo $object_id[1]; ?>" text_id="spanText_<?php echo $object_id[1]; ?>" style="position: absolute;width: 60px;height: 26px;margin: 3px;display:none"><?php echo $getObjects['role']; ?></textarea>
            <span id="spanText_<?php echo $object_id[1]; ?>" class="textHandle" style="font-size: 10px;cursor:pointer;position: absolute;margin: 5px;width: 60px;text-align: center;"><?php echo $getObjects['role']; ?></span>
              <span id="flow_<?php echo $object_id[1]."_".$object_id[2]; ?>" rel="1" class="fl_shapes flowChartObject"></span>
              <span style="position:absolute" class="shapeSideButton_holder flowChartObject">
                  <span style="" class="right flowChartObject connector" id="right_<?php echo $object_id[1]."_".$object_id[2]; ?>"></span>
              </span>
            </span>
            <!--span class="appendShapes flowChartObject" style="z-index:10;margin-left:10px;left:<?php //echo $getObjects['lefts']; ?>;top:<?php //echo $getObjects['tops']; ?>;position:absolute;width: 82px;height: 38px;padding:2px" id="<?php //echo $getObjects['object_id']; ?>">
            <textarea class="textInsert" id="text_<?php //echo $object_id[1]; ?>" text_id="spanText_<?php //echo $object_id[1]; ?>" style="position: absolute;width: 60px;height: 26px;margin: 3px;display:none"><?php //echo $getObjects['role']; ?></textarea>
            <span id="spanText_<?php //echo $object_id[1]; ?>" class="textHandle" style="cursor:pointer;position: absolute;margin: 5px;width: 60px;text-align: center;"><?php //echo $getObjects['role']; ?></span>
              <img src="/images/flowchart/<?php //echo $object_id[2]; ?>.png" id="flow_<?php //echo $object_id[1]."_".$object_id[2]; ?>" rel="1" height="38" width="72" class="fl_shapes flowChartObject" />
              <span style="position:absolute" class="shapeSideButton_holder flowChartObject">
                  <span style="color:red;position:absolute;margin-left:-2px;width:10px;height:10px;padding-left:5px;margin-top:12px;background-color:black" class="right flowChartObject connector" id="right_<?php //echo $object_id[1]."_".$object_id[2]; ?>"></span>
              </span>
            </span>-->
            <?php
        }
        $selectLines = $db->query("SELECT * from tborgchartline where orgChart_id = '$diagram_id' and line_type=1","array");
        foreach($selectLines as $getLines){
            $arrayParent = explode("_",$getLines['master_id']); //split the parent id using the delimiter underscore "_"
            $arrayParent = "line_".$arrayParent[1]; //get the second array element of parent then add "line_" prefix
            $arrayChild = explode("_",$getLines['child_id']); //split the parent id using the delimiter underscore "_"
            $arrayChild = "line_".$arrayChild[1]; //get the second array element of child then add "line_" prefix
            $setClass = $arrayParent."-".$arrayChild; //concat the result of arrayChild and arrayParent
            ?>
            <span class="line <?php echo $setClass; ?>" line-type="<?php echo $getLines['line_type']; ?>" axis="<?php echo $getLines['axis']; ?>" id="<?php echo $getLines['line_id']; ?>" master_id="<?php echo $getLines['master_id']; ?>" child_id="<?php echo $getLines['child_id']; ?>"
                                    style="margin-left:<?php echo $getLines['margin_lefts']; ?>;left:<?php echo $getLines['lefts']; ?>;width:<?php echo $getLines['widths']; ?>;margin-top:<?php echo $getLines['margin_tops']; ?>;top:<?php echo $getLines['tops']; ?>;
                                    position:absolute;height:<?php echo $getLines['heights']; ?>;background-color:rgb(56, 112, 168);"></span>
            <?php
        }
        $selectArrow = $db->query("SELECT * from tborgchartline where orgChart_id = '$diagram_id' and line_type=2","array");
        foreach($selectArrow as $getLinesArrow){
            $arrayParent = explode("_",$getLinesArrow['master_id']); //split the parent id using the delimiter underscore "_"
            $arrayParent = "line_".$arrayParent[1]; //get the second array element of parent then add "line_" prefix
            $arrayChild = explode("_",$getLinesArrow['child_id']); //split the parent id using the delimiter underscore "_"
            $arrayChild = "line_".$arrayChild[1]; //get the second array element of child then add "line_" prefix
            $setClass = $arrayParent."-".$arrayChild; //concat the result of arrayChild and arrayParent
            echo setArrow($getLinesArrow['lefts'],$getLinesArrow['tops'],$setClass,$getLinesArrow['axis'],$getLinesArrow['line_id'],$getLinesArrow['master_id'],$getLinesArrow['child_id'],$getLinesArrow['line_type']);
        }
        ?>
        <script>
            $(".flowchartToolTip").tooltip({
                content: function(callback){
                    role =  $(this).attr("title");
                    a = role
                    $.post("/ajax/actionAdmin",{"action":"getTooltip","role":role},function(data){
                        callback(data);
                    })
                },
                position: {
                    my: "left+15 center", at: "right center"
                },
                open: function( event, ui ) {
                    ui.tooltip.animate({ top: ui.tooltip.position().top + 10 }, "fast" );
                }
            })
        </script>
        <?php
    }elseif($_POST['action']=="getNextUniqueID"){
        $diagram_id = explode("_",$_POST['diagram_id']);
        $countObjects = $db->query("SELECT * from tborgchartobjects where orgChart_id = '$diagram_id[1]'","array");
        $nextID = 1;
        $arrayObjID = array();
        foreach($countObjects as $dataObjects){
            $getMax = explode("_",$dataObjects['object_id']);
            array_push($arrayObjID,$getMax[1]);
        }
        echo max($arrayObjID)+1;
    }elseif($_POST['action']=="getActiveUniqueID"){
        $countObjects = $db->query("SELECT * from tborgchart oc LEFT JOIN tborgchartobjects oco on oc.id=oco.orgChart_id where oc.status=1","array");
        $numrowsObjects = $db->query("SELECT * from tborgchart oc LEFT JOIN tborgchartobjects oco on oc.id=oco.orgChart_id where oc.status=1","numrows");
        if($numrowsObjects==0){
            echo 1;
        }else{
            $nextID = 1;
            $arrayObjID = array();
            foreach($countObjects as $dataObjects){
                $getMax = explode("_",$dataObjects['object_id']);
                array_push($arrayObjID,$getMax[1]);
            }
            echo max($arrayObjID)+1;
        }
        
    }elseif($_POST['action']=="viewActiveDiagram"){
        $activate = $db->query("SELECT * from tborgchart where status = '1' and company_id = '$company_id'","row");
        $diagram_id = $activate['id'];
        $selectObjects = $db->query("SELECT * from tborgchartobjects where orgChart_id = '$diagram_id'","array");
        foreach($selectObjects as $getObjects){
            $object_id = explode("_",$getObjects['object_id'])
            ?>
            <span class="appendShapes flowChartObject appendObjects flowchartToolTip" style="left:<?php echo $getObjects['lefts']; ?>;top:<?php echo $getObjects['tops']; ?>;" id="<?php echo $getObjects['object_id']; ?>" title="<?php echo $getObjects['role']; ?>">
            <textarea class="textInsert" id="text_<?php echo $object_id[1]; ?>" text_id="spanText_<?php echo $object_id[1]; ?>" style="position: absolute;width: 60px;height: 26px;margin: 3px;display:none"><?php echo $getObjects['role']; ?></textarea>
            <span id="spanText_<?php echo $object_id[1]; ?>" class="textHandle" style="font-size: 10px;cursor:pointer;position: absolute;margin: 5px;width: 60px;text-align: center;"><?php echo $getObjects['role']; ?></span>
              <span id="flow_<?php echo $object_id[1]."_".$object_id[2]; ?>" rel="1" class="fl_shapes flowChartObject"></span>
              <span style="position:absolute" class="shapeSideButton_holder flowChartObject">
                  <span style="" class="right flowChartObject connector" id="right_<?php echo $object_id[1]."_".$object_id[2]; ?>"></span>
              </span>
            </span>
            <?php
        }
        $selectLines = $db->query("SELECT * from tborgchartline where orgChart_id = '$diagram_id' and line_type=1","array");
        foreach($selectLines as $getLines){
            $arrayParent = explode("_",$getLines['master_id']); //split the parent id using the delimiter underscore "_"
            $arrayParent = "line_".$arrayParent[1]; //get the second array element of parent then add "line_" prefix
            $arrayChild = explode("_",$getLines['child_id']); //split the parent id using the delimiter underscore "_"
            $arrayChild = "line_".$arrayChild[1]; //get the second array element of child then add "line_" prefix
            $setClass = $arrayParent."-".$arrayChild; //concat the result of arrayChild and arrayParent
            ?>
            <span class="line <?php echo $setClass; ?>" line-type="<?php echo $getLines['line_type']; ?>" axis="<?php echo $getLines['axis']; ?>" id="<?php echo $getLines['line_id']; ?>" master_id="<?php echo $getLines['master_id']; ?>" child_id="<?php echo $getLines['child_id']; ?>"
                                    style="margin-left:<?php echo $getLines['margin_lefts']; ?>;left:<?php echo $getLines['lefts']; ?>;width:<?php echo $getLines['widths']; ?>;margin-top:<?php echo $getLines['margin_tops']; ?>;top:<?php echo $getLines['tops']; ?>;
                                    position:absolute;height:<?php echo $getLines['heights']; ?>;background-color:rgb(56, 112, 168);"></span>
            <?php
        }
        $selectArrow = $db->query("SELECT * from tborgchartline where orgChart_id = '$diagram_id' and line_type=2","array");
        foreach($selectArrow as $getLinesArrow){
            $arrayParent = explode("_",$getLinesArrow['master_id']); //split the parent id using the delimiter underscore "_"
            $arrayParent = "line_".$arrayParent[1]; //get the second array element of parent then add "line_" prefix
            $arrayChild = explode("_",$getLinesArrow['child_id']); //split the parent id using the delimiter underscore "_"
            $arrayChild = "line_".$arrayChild[1]; //get the second array element of child then add "line_" prefix
            $setClass = $arrayParent."-".$arrayChild; //concat the result of arrayChild and arrayParent
            echo setArrow($getLinesArrow['lefts'],$getLinesArrow['tops'],$setClass,$getLinesArrow['axis'],$getLinesArrow['line_id'],$getLinesArrow['master_id'],$getLinesArrow['child_id'],$getLinesArrow['line_type']);
        }
        ?>
        <script>
            $(".flowchartToolTip").tooltip({
                content: function(callback){
                    role =  $(this).attr("title");
                    a = role
                    $.post("/ajax/actionAdmin",{"action":"getTooltip","role":role},function(data){
                        callback(data);
                    })
                },
                position: {
                    my: "left+15 center", at: "right center"
                },
                open: function( event, ui ) {
                    ui.tooltip.animate({ top: ui.tooltip.position().top + 10 }, "fast" );
                }
            })
        </script>
        <?php
    }elseif($_POST['action']=="activateDiagram"){
        $diagram_id = $_POST['diagram_id'];
        //OLD ACTIVE DIAGRAM
        //to get the top node of the orchart
        $getActiveOrgChart = $db->query("SELECT id FROM tborgchart where is_active = 1 and company_id='$company_id' and status=1","row");
        $queryObject = $db->query("SELECT object_id from tborgchartobjects where orgchart_id = '".$getActiveOrgChart['id']."'","array");
        $queryRows = $db->query("SELECT object_id from tborgchartobjects where orgchart_id = '".$getActiveOrgChart['id']."'","numrows");
        $count = 0;
        $countError = array();
        $object = array();
        $topNode = "";
        $sequencialOrgChart = array();
        foreach($queryObject as $data){
            $queryLines = $db->query("SELECT DISTINCT(child_id) FROM tborgchartline where orgchart_id = '".$getActiveOrgChart['id']."'","array");
            foreach($queryLines as $dataLines){
                if($dataLines['child_id']!=$data['object_id']){
                    $count++;
                }
            }
            array_push($countError,$count);
            array_push($object,$data['object_id']);
            $count = 0;
        }
        for($a=0;$a<$queryRows;$a++){
            if($countError[$a]+1==$queryRows){
                $topNode =  $object[$a];
                break;
            }
        }
        $loopRange = $db->query("select distinct(master_id) FROM tborgchartline where orgChart_id = '".$getActiveOrgChart['id']."'","numrows");
        $arrayChilds = array();
        $arrayGroups = array();
        $queryRole = $db->query("SELECT role FROM tborgchartobjects where object_id='$topNode' and orgchart_id = '".$getActiveOrgChart['id']."'","row");
        array_push($sequencialOrgChart,"Master->".$queryRole['role']);
        $sequenceCounter = 1;
        for($a=0;$a<$loopRange;$a++){
            if($a==0){
                $queryLines = $db->query("SELECT DISTINCT(child_id) FROM tborgchartline where master_id = '$topNode' and orgchart_id = '".$getActiveOrgChart['id']."'","array");
                foreach($queryLines as $dataqueryLines){
                    $queryRole = $db->query("SELECT role FROM tborgchartobjects where object_id='".$dataqueryLines['child_id']."' and orgchart_id = '".$getActiveOrgChart['id']."'","row");
                    $queryMasterNode = $db->query("SELECT role FROM tborgchartobjects where object_id='$topNode' and orgchart_id = '".$getActiveOrgChart['id']."'","row");
                    //echo $queryRole['role'].",";
                    array_push($arrayChilds,$dataqueryLines['child_id']);
                    array_push($sequencialOrgChart,$queryMasterNode['role']."->".$queryRole['role']);
                }    
            }else{
                for($c=0;$c<count($arrayChilds);$c++){
                    $query = $db->query("SELECT DISTINCT(child_id) FROM tborgchartline where master_id = '$arrayChilds[$c]' and orgchart_id = '".$getActiveOrgChart['id']."'","array");
                    $sequenceCounter++;
                    foreach($query as $data){
                        $queryRole = $db->query("SELECT role FROM tborgchartobjects where object_id='".$data['child_id']."' and orgchart_id = '".$getActiveOrgChart['id']."'","row");
                        $queryMasterRole = $db->query("SELECT role FROM tborgchartobjects where object_id='".$arrayChilds[$c]."' and orgchart_id = '".$getActiveOrgChart['id']."'","row");
                        //echo $queryMasterRole['role']."->".$queryRole['role'].",";
                        array_push($arrayChilds,$data['child_id']);
                        
                        array_push($sequencialOrgChart,$queryMasterRole['role']."->".$queryRole['role']);
                        
                    }
                    //echo "\n";
                    
                }
                $arrayChilds = array();
                $arrayChilds = array();
            }
            //echo "\n";
        }
        //NEW ACTIVE DIAGRAM
        //to get the top node of the orchart
        $queryObject = $db->query("SELECT object_id from tborgchartobjects where orgchart_id = '$diagram_id'","array");
        $queryRows = $db->query("SELECT object_id from tborgchartobjects where orgchart_id = '$diagram_id'","numrows");
        $count = 0;
        $countError = array();
        $object = array();
        $topNode = "";
        $sequencialOrgChartNew = array();
        foreach($queryObject as $data){
            $queryLines = $db->query("SELECT DISTINCT(child_id) FROM tborgchartline where orgchart_id = '$diagram_id'","array");
            foreach($queryLines as $dataLines){
                if($dataLines['child_id']!=$data['object_id']){
                    $count++;
                }
            }
            array_push($countError,$count);
            array_push($object,$data['object_id']);
            $count = 0;
        }
        for($a=0;$a<$queryRows;$a++){
            if($countError[$a]+1==$queryRows){
                $topNode =  $object[$a];
                break;
            }
        }
        $loopRange = $db->query("select distinct(master_id) FROM tborgchartline where orgChart_id = '$diagram_id'","numrows");
        $arrayChilds = array();
        $arrayGroups = array();
        $queryRole = $db->query("SELECT role FROM tborgchartobjects where object_id='$topNode' and orgchart_id = '$diagram_id'","row");
        array_push($sequencialOrgChartNew,"Master->".$queryRole['role']);
        $sequenceCounter = 1;
        for($a=0;$a<$loopRange;$a++){
            if($a==0){
                $queryLines = $db->query("SELECT DISTINCT(child_id) FROM tborgchartline where master_id = '$topNode' and orgchart_id = '$diagram_id'","array");
                foreach($queryLines as $dataqueryLines){
                    $queryRole = $db->query("SELECT role FROM tborgchartobjects where object_id='".$dataqueryLines['child_id']."' and orgchart_id = '$diagram_id'","row");
                    $queryMasterNode = $db->query("SELECT role FROM tborgchartobjects where object_id='$topNode' and orgchart_id = '$diagram_id'","row");
                    //echo $queryRole['role'].",";
                    array_push($arrayChilds,$dataqueryLines['child_id']);
                    array_push($sequencialOrgChartNew,$queryMasterNode['role']."->".$queryRole['role']);
                }    
            }else{
                for($c=0;$c<count($arrayChilds);$c++){
                    $query = $db->query("SELECT DISTINCT(child_id) FROM tborgchartline where master_id = '$arrayChilds[$c]' and orgchart_id = '$diagram_id'","array");
                    $sequenceCounter++;
                    foreach($query as $data){
                        $queryRole = $db->query("SELECT role FROM tborgchartobjects where object_id='".$data['child_id']."' and orgchart_id = '$diagram_id'","row");
                        $queryMasterRole = $db->query("SELECT role FROM tborgchartobjects where object_id='".$arrayChilds[$c]."' and orgchart_id = '$diagram_id'","row");
                        //echo $queryMasterRole['role']."->".$queryRole['role'].",";
                        array_push($arrayChilds,$data['child_id']);
                        
                        array_push($sequencialOrgChartNew,$queryMasterRole['role']."->".$queryRole['role']);
                        
                    }
                    //echo "\n";
                    
                }
                $arrayChilds = array();
                $arrayChilds = array();
            }
            //echo "\n";
        }
        /*print_r($sequencialOrgChart);
        print_r($sequencialOrgChartNew);*/
        $merge = array();
        //echo "---------------------------------- \n";
        //echo "Active Organizational Chart \n";
        foreach($sequencialOrgChartNew as $k => $v){
            $merge[$k] = $v;
            //
            $merge2Array = explode("->",$v);
            $merge2[$k] = $merge2Array[1];
            //echo $v . "\n";
        }
        
        //echo "---------------------------------- \n";
        //echo "\n";
        //echo "---------------------------------- \n";
        $deletedRole = array();
        $updatedRole = array();
        foreach($sequencialOrgChart as $k => $v){
            //update and delete
            if(in_array($v,$merge)==false){
                //echo $v . "\n";
                $updatedArray = explode("->",$v);
                array_push($updatedRole,$updatedArray[1]);
            }
            //delete
            $valueArray = explode("->",$v);
            if(in_array($valueArray[1],$merge2)==false){
                //echo $valueArray[1]."\n";
                array_push($deletedRole,$valueArray[1]);
            }
        }
        $COuntDeleted = 0;
        foreach($deletedRole as $key=>$values){
            $selectPendingRequest = $db->query("SELECT * FROM tbrequest r
                                               LEFT JOIN tbrequest_process rp on rp.request_id = r.id
                                               where rp.status = 0 and r.company_id = 1 and rp.approver like '%".$values."%'","numrows");
            if($selectPendingRequest>0){
                $COuntDeleted++;
            }
        }
        if($COuntDeleted>0){
            echo "<+>"; //Admin want to delete node but has a pending request
        }else{
            //Search the valid node to update
            $trueNodesToUpdate = array();
            $countUpdate = 0;
            foreach($updatedRole as $key=>$value){
                if(in_array($value,$deletedRole)==false){
                    array_push($trueNodesToUpdate,$value);
                    $countUpdate++;
                }
            }
            //Reset Requests
            $countUpdateRequest = 0;
            if($countUpdate>0){
                foreach($trueNodesToUpdate as $k => $value){
                    $getMasterObjectID = $db->query("SELECT object_id from tborgchartobjects where role='$value'","row");
                    $getMasterRole = $db->query("SELECT * from tborgchartobjects oo left join tborgchartline ol on oo.object_id = ol.master_id where oo.orgChart_id = '".$getActiveOrgChart['id']."' and ol.orgChart_id = '".$getActiveOrgChart['id']."' and ol.child_id = '".$getMasterObjectID['object_id']."'","row");
                    $requestQuery = $db->query("SELECT f.workflow_id as workflow_id, rp.approver as past_approver, u.role_type as role_type, r.id as id, u.role as user_reques_role,oo.object_id as object_id  FROM `tbrequest` r LEFT JOIN `tbrequest_process` rp on r.id = rp.request_id LEFT JOIN tbuser u on r.user_id = u.id left join tborgchartobjects oo on oo.role=u.role LEFT JOIN tbform f on f.id = r.form_id where r.status=0 and oo.orgChart_id = '".$getActiveOrgChart['id']."' and rp.approver like '%".$getMasterRole['role']."%' and oo.orgChart_id = '".$getActiveOrgChart['id']."'","array");
                    $requestRow = $db->query("SELECT rp.approver as past_approver, u.role_type as role_type, r.id as id, u.role as user_reques_role,oo.object_id as object_id  FROM `tbrequest` r LEFT JOIN `tbrequest_process` rp on r.id = rp.request_id LEFT JOIN tbuser u on r.user_id = u.id left join tborgchartobjects oo on oo.role=u.role where r.status=0 and oo.orgChart_id = '".$getActiveOrgChart['id']."' and rp.approver like '%".$getMasterRole['role']."%' and oo.orgChart_id = '".$getActiveOrgChart['id']."'","numrows");
                    
                    foreach($requestQuery as $requestData){
                        //echo $requestData['id']." ".$requestData['user_reques_role']." ".$requestData['role_type']." ".$requestData['workflow_id']."\n";
                        $getObjectID = $db->query("SELECT object_id from tborgchartobjects where role='".$requestData['user_reques_role']."' and orgChart_id='".$diagram_id."'","row");
                        $d = 0;
                        $arrayWorkflowRole = array();
                        $arrayWorkflowRoleStatus = array();
                        $arrayOrgchart = array();
                        $arrayWorkflowObjID = array();
                        $push = false;
                        while(true){
                            if($d==0){
                                $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = 'flowspan_1_worklow' and worflow_id = '".$requestData['workflow_id']."'","row");    
                            }else{
                                $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = '".$master['child_id']."' and worflow_id = '".$requestData['workflow_id']."'","row");    
                            }
                            $queryMasterNode = $db->query("SELECT * FROM tbworflow_obects where object_id='".$master['child_id']."' and worflow_id = '".$requestData['workflow_id']."'","row");
                            if($queryMasterNode['role']=="END"){
                                break;
                            }else{
                                //echo $queryMasterNode['role']."\n";
                                if($queryMasterNode['role']=="Head" || $queryMasterNode['role']=="Assistant Head"){
                                    //for the the submitter
                                    if($d==0 and $requestData['role_type']!=1){ //hindi head
                                        $dept = $requestData['user_reques_role'];
                                        $masterOrgChart = $db->query("SELECT object_id FROM tborgchartobjects where role='".$requestData['user_reques_role']."' and orgChart_id = '".$diagram_id."'","row");
                                    }else{
                                        if($d==0){
                                            $masterOrgChart = $db->query("SELECT master_id FROM tborgchartline where child_id = '".$getObjectID['object_id']."' and orgChart_id = '".$diagram_id."'","row");    
                                        }else{
                                            $masterOrgChart = $db->query("SELECT master_id FROM tborgchartline where (child_id = '".$masterOrgChart['master_id']."' || child_id='".$masterOrgChart['object_id']."') and orgChart_id = '".$diagram_id."'","row");
                                        }
                                        $queryMasterNodeOrgChart = $db->query("SELECT * FROM tborgchartobjects where object_id='".$masterOrgChart['master_id']."' and orgChart_id = '".$diagram_id."'","row");
                                        $dept = $queryMasterNodeOrgChart['role'];
                                        
                                    }
                                    //echo $queryMasterNode['role']."_".$dept."->".$master['child_id']."++".$nextMaster_id[$a]."\n\n";
                                }else{
                                    $dept = "";
                                    //echo $queryMasterNode['role']."->".$master['child_id']."++".$nextMaster_id[$a]."\n\n";
                                }
                            }
                            //echo $queryMasterNode['role'].$dept."->".$master['child_id']."++".$nextMaster_id[$a]."\n\n";
                            array_push($arrayWorkflowRole,$queryMasterNode['role']);
                            array_push($arrayWorkflowRoleStatus,$queryMasterNode['status']);
                            array_push($arrayWorkflowObjID,$master['child_id']);
                            array_push($arrayOrgchart,$dept);
                            $d++;
                        }
                        $minus = 0;
                        //temporary get the flow of the approver
                        $roleToInserts = "";$object_id2 = "";$lastApproverCount=0;$getRowsApprover = 0;$confirmation=0;$confirm = 0;$proceedToNext = 0;$approverFlow = "";$requestFlowApprover ="";$requestFlowObj_id="";
                        for($o=0;$o<count($arrayWorkflowRole);$o++){
                            if($arrayWorkflowRole[$o]=="Head" || $arrayWorkflowRole[$o]=="Assistant Head"){
                                if($arrayWorkflowRole[$o]=="Head" and $arrayWorkflowRole[$o-1]=="Assistant Head"){
                                    $minus++;
                                }
                                $roleToInserts = $arrayWorkflowRole[$o]."_".$arrayOrgchart[$o-$minus];
                                
                                $getRowsApprover = $db->query("SELECT * FROM tbuser where role_type='".tempGroupType($arrayWorkflowRole[$o])."' and role='".$arrayOrgchart[$o-$minus]."' and is_active=1 and status =1 and company_id = '$company_id'","numrows");
                                //echo $roleToInserts."->".$getRowsApprover."\n";
                                $appFlow = $arrayWorkflowObjID[$o];
                                $approver = $arrayWorkflowRole[$o]."_".$arrayOrgchart[$o-$minus];
                                if($getRowsApprover>0){
                                    
                                    $lastApproverCount++;
                                    
                                }
                            }else{
                                $roleToInserts = $arrayWorkflowRole[$o];
                                $getRowsApprover = $db->query("SELECT * FROM tbuser u LEFT JOIN tbposition p on u.position_id = p.id where (concat_ws(' ',u.firstname,u.lastname) = '".$roleToInserts."' or p.position = '".$roleToInserts."') and u.is_active=1 and u.status =1 and u.company_id = $company_id","numrows");
                                //echo $roleToInserts."->".$getRowsApprover."\n";
                                $appFlow = $arrayWorkflowObjID[$o];
                                $approver = $arrayWorkflowRole[$o];
                                if($getRowsApprover>0){
                                    $lastApproverCount++;
                                }
                            }
                            $requestFlowObj_id.=$appFlow."<->";
                            $requestFlowApprover.=$approver."<->";
                        }
                        $minus = 0;
                        //for insert the first approver
                        $roleToInserts = "";$object_id2 = "";$lastApproverCount=0;$getRowsApprover = 0;$confirmation=0;$confirm = 0;$proceedToNext = 0;$approverFlow = "";
                        for($o=0;$o<count($arrayWorkflowRole);$o++){
                            if($arrayWorkflowRole[$o]=="Head" || $arrayWorkflowRole[$o]=="Assistant Head"){
                                if($arrayWorkflowRole[$o]=="Head" and $arrayWorkflowRole[$o-1]=="Assistant Head"){
                                    $minus++;
                                }
                                $roleToInserts = $arrayWorkflowRole[$o]."_".$arrayOrgchart[$o-$minus];
                                $getRowsApprover = $db->query("SELECT * FROM tbuser where role_type='".tempGroupType($arrayWorkflowRole[$o])."' and role='".$arrayOrgchart[$o-$minus]."' and is_active=1 and status =1 and company_id = '$company_id'","numrows");
                                //echo $roleToInserts."->".$getRowsApprover."\n";
                                if($getRowsApprover>0){
                                    $lastApproverCount++;
                                    $approver = $arrayWorkflowRole[$o]."_".$arrayOrgchart[$o-$minus];
                                }
                            }else{
                                $roleToInserts = $arrayWorkflowRole[$o];
                                $getRowsApprover = $db->query("SELECT * FROM tbuser u LEFT JOIN tbposition p on u.position_id = p.id where (concat_ws(' ',u.firstname,u.lastname) = '".$roleToInserts."' or p.position = '".$roleToInserts."') and u.is_active=1 and u.status =1 and u.company_id = $company_id","numrows");
                                //echo $roleToInserts."->".$getRowsApprover."\n";
                                if($getRowsApprover>0){
                                   $approver = $arrayWorkflowRole[$o];
                                   $lastApproverCount++;
                                }
                            }
                            if($o==0 && $getRowsApprover==0){
                                $confirm = 1;
                            }
                            if($getRowsApprover>0){
                                $approverStatus = $arrayWorkflowRoleStatus[$o];
                                $master_id = $arrayWorkflowObjID[$o];
                                $proceedToNext++;
                                //echo $approver;
                                break;
                            }
                        }
                        //update flow
                        $updateFlow = array(
                            "requestFlowApprover"=>$requestFlowApprover
                        );
                        $whereFlow = array(
                            "id"=>$requestData['id']
                        );
                        $db->update("tbrequest",$updateFlow,$whereFlow);
                        //echo $requestData['id']." ".$requestFlowApprover."\n";
                        $deleteRequestArray = array(
                                    "request_id"=>$requestData['id']                
                                    );
                        $db->delete("tbrequest_process",$deleteRequestArray);
                        $insertRequestProcess = array(
                                "request_id"=>$requestData['id'],
                                "approver"=>$approver,
                                "wf_master_id"=>$master_id,
                                "status"=>0
                        );
                        $db->insert("tbrequest_process",$insertRequestProcess);
                        $countUpdateRequest++;
                    }
                    $updateActiveOrgChart++;
                    /*//echo $value;
                    $getMasterObjectID = $db->query("SELECT object_id from tborgchartobjects where role='$value'","row");
                    $getMasterRole = $db->query("SELECT * from tborgchartobjects oo left join tborgchartline ol on oo.object_id = ol.master_id where oo.orgChart_id = '".$getActiveOrgChart['id']."' and ol.orgChart_id = '".$getActiveOrgChart['id']."' and ol.child_id = '".$getMasterObjectID['object_id']."'","row");
                    $requestQuery = $db->query("SELECT f.workflow_id as workflow_id, rp.approver as past_approver, u.role_type as role_type, r.id as id, u.role as user_reques_role,oo.object_id as object_id  FROM `tbrequest` r LEFT JOIN `tbrequest_process` rp on r.id = rp.request_id LEFT JOIN tbuser u on r.user_id = u.id left join tborgchartobjects oo on oo.role=u.role LEFT JOIN tbform f on f.id = r.form_id where r.status=0 and oo.orgChart_id = '".$getActiveOrgChart['id']."' and rp.approver like '%".$getMasterRole['role']."%' and oo.orgChart_id = '".$getActiveOrgChart['id']."'","array");
                    $requestRow = $db->query("SELECT rp.approver as past_approver, u.role_type as role_type, r.id as id, u.role as user_reques_role,oo.object_id as object_id  FROM `tbrequest` r LEFT JOIN `tbrequest_process` rp on r.id = rp.request_id LEFT JOIN tbuser u on r.user_id = u.id left join tborgchartobjects oo on oo.role=u.role where r.status=0 and oo.orgChart_id = '".$getActiveOrgChart['id']."' and rp.approver like '%".$getMasterRole['role']."%' and oo.orgChart_id = '".$getActiveOrgChart['id']."'","numrows");
                    foreach($requestQuery as $requestData){
                        $getNewMasterRole = $db->query("SELECT oo.role as role,oo.object_id as object_id from tborgchartobjects oo left join tborgchartline ol on oo.object_id = ol.master_id where oo.orgChart_id = '$diagram_id' and ol.orgChart_id = '$diagram_id' and ol.child_id = '".$requestData['object_id']."'","row");
                        if(roleType($requestData['role_type'])=="Head"){
                            $approverDept = $getNewMasterRole['role'];
                        }else{
                            $approverDept = $requestData['user_reques_role'];
                        }
                        //FOR WORKFLOW
                        $selectFirstApproverObject = $db->query("SELECT child_id FROM tbworkflow_line where master_id = 'flowspan_1_worklow' and worflow_id = '".$requestData['workflow_id']."'","row");
                        $selectFirstApproverRole = $db->query("SELECT role,object_id from tbworflow_obects where object_id='".$selectFirstApproverObject['child_id']."' AND worflow_id='".$requestData['workflow_id']."'","row");
                        $newApprover = $selectFirstApproverRole['role']."_".$approverDept;
                        $wf_master_id = $selectFirstApproverRole['object_id'];
                        //echo $getNewMasterRole['object_id'];
                        //echo "Reset".$requestData['id']."to approver: ".$getNewMasterRole['role'].",";
                        $deleteRequestArray = array(
                                    "request_id"=>$requestData['id']                
                                    );
                        //$db->delete("tbrequest_process",$deleteRequestArray);
                        $insertRequestProcess = array(
                                "request_id"=>$requestData['id'],
                                "approver"=>$newApprover,
                                "wf_master_id"=>$wf_master_id,
                                "status"=>0
                        );
                        //$db->insert("tbrequest_process",$insertRequestProcess);
                        $countUpdateRequest++;
                    }
                    //echo "\n";
                    $updateActiveOrgChart++;
                    */
                }
            }
            //Update Node
            $updateActiveOrgChart++;
        }
        //echo $countUpdate;
        if($updateActiveOrgChart>0){
            $update = array(
                "status"=>0
                );
            $condition = array(
                "company_id"=>$company_id
                );
            $db->update("tborgchart",$update,$condition);
            $updateTrue = array(
                "status"=>1
                );
            $conditionTrue = array(
                "id"=>$diagram_id
                );
            $db->update("tborgchart",$updateTrue,$conditionTrue);
            if($countUpdateRequest>0){
                echo "<request>"; //Update of Orgchart Done, Some request will be reset
            }else{
                echo "Update Done";    
            }
        }
        
    }elseif($_POST['action']=="deleteDiagram"){
        $diagram_id = $_POST['diagram_id'];
        $orgObjDelete = array(
            "orgChart_id"=>$diagram_id
            );
        $orgDelete = array(
            "id"=>$diagram_id
        );
        //delete fields!!
        $db->delete("tborgchart",$orgDelete);
        $db->delete("tborgchartline",$orgObjDelete);
        $db->delete("tborgchartobjects",$orgObjDelete);
        //echo "Delete action has a comment =)";
        
    }elseif($_POST['action']=="getActiveDiagram"){
        $activate = $db->query("SELECT * from tborgchart where status = '1' and company_id = '$company_id'","row");
        echo $activate['id'];
    }
}
?>